#include "qenumproperty.h"

#include "../../libs/sharedLib/qcommonstruct.h"

#include <QComboBox>
#include <QIcon>

QEnumEditor::QEnumEditor(const ComboItems &items):
    QComboBox(NULL)
{
    foreach(tagComboItem item,items)
    {
        addItem(QIcon(item.m_icon),item.m_text);
    }
    m_items=items;
}

void QEnumEditor::setValue(const QVariant &value)
{
    m_value=value;
    foreach(tagComboItem item,m_items)
    {
        if(item.m_value==value)
        {
            this->setCurrentIndex(this->findText(item.m_text));
            return;
        }
    }
}

QVariant QEnumEditor::value()
{
    return m_value;
}

QEnumProperty::QEnumProperty(SHAREDLIB::QAbstractProperty *parent):
    SHAREDLIB::QAbstractProperty(parent)
{
    connect(this,SIGNAL(showValueChanged()),this,SLOT(value_changed()));
}

void QEnumProperty::valueXML(QXmlStreamWriter *w)
{
    w->writeAttribute("value",getValue().toString());
}

QWidget* QEnumProperty::getEditor()
{
    if(attribute("editabled").toBool())
    {

        ComboItems items=this->attribute("items").value<ComboItems>();
        QEnumEditor* b=new QEnumEditor(items);
        connect(b,SIGNAL(currentIndexChanged(QString)),this,SLOT(editorValueChanged(QString)));
        m_editor=b;
    }
    return QAbstractProperty::getEditor();
}

void QEnumProperty::editorValueChanged(const QString &text)
{
    if(text!=getValue().toString())
    {
        ComboItems items=this->attribute("items").value<ComboItems>();
        foreach(tagComboItem item,items)
        {
            if(item.m_text==text)
            {
                setSignalValue(item.m_value);
            }
        }
    }
}

QIcon QEnumProperty::valueIcon()
{
    ComboItems items=this->attribute("items").value<ComboItems>();
    foreach(tagComboItem item,items)
    {
        if(item.m_value==getValue())
        {
            return QIcon(item.m_icon);
        }
    }
    return QIcon();
}

QString QEnumProperty::valueText()
{
    ComboItems items=this->attribute("items").value<ComboItems>();
    foreach(tagComboItem item,items)
    {
        if(item.m_value==getValue())
        {
            return item.m_text;
        }
    }
    return "";
}

void QEnumProperty::value_changed()
{
    QEnumEditor* e=(QEnumEditor*)m_editor;
    if(e!=NULL)
    {
        e->setValue(m_value);
    }
}
